import {
  createRouter,
  createWebHistory,
  type NavigationGuardNext,
  type RouteLocationNormalized,
} from 'vue-router'
import Loayout from '@/views/Home/Loayout.vue'
import Login from '@/views/Login/Login.vue'
import { ElNotification } from 'element-plus'
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: Loayout,
      children: [
        {
          path: '/journalism',
          name: 'journalism',
          component: () => import('@/views/JournaLism/index.vue'),
        },
        {
          path: '/issue',
          name: 'issue',
          component: () => import('@/views/Issue/index.vue'),
        },
        {
          path: '/alreadyIssue',
          name: 'alreadyIssue',
          component: () => import('@/views/AlreadyIssue/index.vue'),
        },
        {
          path: '/i18n',
          name: 'i18n',
          component: () => import('@/views/I18n/index.vue'),
        }
      ],
    },
    {
      path: '/preview',
      name: 'preview',
      component: () => import('@/views/Issue/Preview.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login/Login.vue'),
    },
    {
      path: '/viewdetails',
      name: 'viewdetails',
      component: () => import('@/components/AlreadyIssue/ViewDetails.vue'),
    }
  ],
})

router.beforeEach(
  (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    if (to.path === '/login' || to.path === '/preview' || to.path === '/viewdetails') {
      next()
      return
    }

    try {
      const loginData = localStorage.getItem('login')
      if (!loginData) {
        ElNotification({
          title: '提示',
          message: '请先登录',
          type: 'warning',
        })
        next('/login')
        return
      }

      const { access_token } = JSON.parse(loginData)
      if (!access_token) {
        ElNotification({
          title: '提示',
          message: '登录信息无效，请重新登录',
          type: 'warning',
        })
        localStorage.removeItem('login')
        next('/login')
        return
      }

      const isTokenExpired = () => {
        try {
          const tokenParts = access_token.split('.')
          if (tokenParts.length !== 3) {
            return true
          }

          const payload = JSON.parse(
            atob(
              tokenParts[1].replace(/-/g, '+').replace(/_/g, '/') +
                '==='.slice(0, (4 - (tokenParts[1].length % 4)) % 4),
            ),
          )
          if (payload.exp) {
            const currentTime = Math.floor(Date.now() / 1000)
            return currentTime > payload.exp
          }

          return false
        } catch (error) {
          console.error('解析token失败:', error)
          return true
        }
      }

      if (isTokenExpired()) {
        ElNotification({
          title: '提示',
          message: '登录已过期，请重新登录',
          type: 'warning',
        })
        localStorage.removeItem('login')
        next('/login')
        return
      }

      next()
    } catch (error) {
      console.error('路由守卫错误:', error)
      localStorage.removeItem('login')
      next('/login')
    }
  },
)

export default router
